package com.mfw.springboot.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mfw.springboot.annotation.AuthCheck;
import com.mfw.springboot.common.*;
import com.mfw.springboot.constant.UserConstant;
import com.mfw.springboot.exception.BusinessException;
import com.mfw.springboot.exception.ThrowUtils;
import com.mfw.springboot.mapper.UserClassRelationMapper;
import com.mfw.springboot.model.dto.userClassRelation.*;
import com.mfw.springboot.model.entity.User;
import com.mfw.springboot.model.entity.UserClassRelation;
import com.mfw.springboot.model.vo.UserClassRelationVO;
import com.mfw.springboot.service.UserClassRelationService;
import com.mfw.springboot.service.UserService;
import com.mfw.springboot.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 用户班级关系接口
 *
 * @author mfw
 * @from <a href="https://gitee.com/hanhuaifei/projects">我的gitee</a>
 * @Date 2024/9/26
 */
@RestController
@RequestMapping("/userClassRelation")
@Slf4j
public class UserClassRelationController {

    @Resource
    private UserClassRelationService userClassRelationService;

    @Resource
    private UserClassRelationMapper userClassRelationMapper;

    @Resource
    private UserService userService;

    /**
     * 根据classIdList 获取 userIdList
     *
     * @param userQueryByClassRequest
     * @return
     */
    @PostMapping("/list/user")
    public BaseResponse<List<Long>> listUserIdListByClassIdList(@RequestBody UserQueryByClassRequest userQueryByClassRequest) {
        ThrowUtils.throwIf(userQueryByClassRequest == null, ErrorCode.PARAMS_ERROR);

        List<Long> classIdList = userQueryByClassRequest.getClassIdList();

        QueryWrapper<UserClassRelation> wrapper = new QueryWrapper<>();

        wrapper.in("class_id",classIdList);

        List<Long> userIdList = userClassRelationService.list(wrapper).stream()
                .map(UserClassRelation::getUserId)
                .collect(Collectors.toList());

        // 获取封装类
        return Result.success(userIdList);
    }


    /**
     * 创建用户班级关系
     *
     * @param userClassRelationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Long> joinUserClassRelation(@RequestBody UserClassRelationAddRequest userClassRelationAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userClassRelationAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        UserClassRelation userClassRelation = new UserClassRelation();
        BeanUtils.copyProperties(userClassRelationAddRequest, userClassRelation);
        // 数据校验
        userClassRelationService.validUserClassRelation(userClassRelation, true);

        //若已经加入,报错
        QueryWrapper<UserClassRelation> wrapper = new QueryWrapper<>();
        wrapper.eq("user_id", userClassRelation.getUserId());
        wrapper.eq("class_id", userClassRelation.getClassId());
        UserClassRelation dbUserClassRelation = userClassRelationService.getOne(wrapper);
        ThrowUtils.throwIf(dbUserClassRelation != null, ErrorCode.OPERATION_ERROR, "已经加入该班级");

        // 写入数据库
        boolean result = userClassRelationService.save(userClassRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserClassRelationId = userClassRelation.getId();
        return Result.success(newUserClassRelationId);
    }


    // region 增删改查

    /**
     * 创建用户班级关系
     *
     * @param userClassRelationAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addUserClassRelation(@RequestBody UserClassRelationAddRequest userClassRelationAddRequest, HttpServletRequest request) {
        ThrowUtils.throwIf(userClassRelationAddRequest == null, ErrorCode.PARAMS_ERROR);
        // 在此处将实体类和 DTO 进行转换
        UserClassRelation userClassRelation = new UserClassRelation();
        BeanUtils.copyProperties(userClassRelationAddRequest, userClassRelation);
        // 数据校验
        userClassRelationService.validUserClassRelation(userClassRelation, true);

        // 写入数据库
        boolean result = userClassRelationService.save(userClassRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        // 返回新写入的数据 id
        long newUserClassRelationId = userClassRelation.getId();
        return Result.success(newUserClassRelationId);
    }

    /**
     * 删除用户班级关系
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUserClassRelation(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        UserClassRelation oldUserClassRelation = userClassRelationService.getById(id);
        ThrowUtils.throwIf(oldUserClassRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldUserClassRelation.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userClassRelationService.removeById(id);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 更新用户班级关系（仅管理员可用）
     *
     * @param userClassRelationUpdateRequest
     * @return
     */
    @PostMapping("/update")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Boolean> updateUserClassRelation(@RequestBody UserClassRelationUpdateRequest userClassRelationUpdateRequest) {
        if (userClassRelationUpdateRequest == null || userClassRelationUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        UserClassRelation userClassRelation = new UserClassRelation();
        BeanUtils.copyProperties(userClassRelationUpdateRequest, userClassRelation);
        // 数据校验
        userClassRelationService.validUserClassRelation(userClassRelation, false);
        // 判断是否存在
        long id = userClassRelationUpdateRequest.getId();
        UserClassRelation oldUserClassRelation = userClassRelationService.getById(id);
        ThrowUtils.throwIf(oldUserClassRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 操作数据库
        boolean result = userClassRelationService.updateById(userClassRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 根据 id 获取用户班级关系（封装类）
     *
     * @param id
     * @return
     */
    @GetMapping("/get/vo")
    public BaseResponse<UserClassRelationVO> getUserClassRelationVOById(long id, HttpServletRequest request) {
        ThrowUtils.throwIf(id <= 0, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        UserClassRelation userClassRelation = userClassRelationService.getById(id);
        ThrowUtils.throwIf(userClassRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 获取封装类
        return Result.success(userClassRelationService.getUserClassRelationVO(userClassRelation, request));
    }

    /**
     * 分页获取用户班级关系列表（仅管理员可用）
     *
     * @param userClassRelationQueryRequest
     * @return
     */
    @PostMapping("/list/page")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public BaseResponse<Page<UserClassRelation>> listUserClassRelationByPage(@RequestBody UserClassRelationQueryRequest userClassRelationQueryRequest) {
        long current = userClassRelationQueryRequest.getCurrent();
        long size = userClassRelationQueryRequest.getPageSize();
        // 查询数据库
        Page<UserClassRelation> userClassRelationPage = userClassRelationService.page(new Page<>(current, size),
                userClassRelationService.getQueryWrapper(userClassRelationQueryRequest));
        return Result.success(userClassRelationPage);
    }

    /**
     * 分页获取用户班级关系列表（封装类）
     *
     * @param userClassRelationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/list/page/vo")
    public BaseResponse<Page<UserClassRelationVO>> listUserClassRelationVOByPage(@RequestBody UserClassRelationQueryRequest userClassRelationQueryRequest,
                                                                                 HttpServletRequest request) {
        long current = userClassRelationQueryRequest.getCurrent();
        long size = userClassRelationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserClassRelation> userClassRelationPage = userClassRelationService.page(new Page<>(current, size),
                userClassRelationService.getQueryWrapper(userClassRelationQueryRequest));
        // 获取封装类
        return Result.success(userClassRelationService.getUserClassRelationVOPage(userClassRelationPage, request));
    }

    /**
     * 分页获取当前登录用户创建的用户班级关系列表
     *
     * @param userClassRelationQueryRequest
     * @param request
     * @return
     */
    @PostMapping("/my/list/page/vo")
    public BaseResponse<Page<UserClassRelationVO>> listMyUserClassRelationVOByPage(@RequestBody UserClassRelationQueryRequest userClassRelationQueryRequest,
                                                                                   HttpServletRequest request) {
        ThrowUtils.throwIf(userClassRelationQueryRequest == null, ErrorCode.PARAMS_ERROR);
        // 补充查询条件，只查询当前登录用户的数据
        User loginUser = userService.getLoginUser(request);
        userClassRelationQueryRequest.setUserId(loginUser.getId());
        long current = userClassRelationQueryRequest.getCurrent();
        long size = userClassRelationQueryRequest.getPageSize();
        // 限制爬虫
        ThrowUtils.throwIf(size > 20, ErrorCode.PARAMS_ERROR);
        // 查询数据库
        Page<UserClassRelation> userClassRelationPage = userClassRelationService.page(new Page<>(current, size),
                userClassRelationService.getQueryWrapper(userClassRelationQueryRequest));
        // 获取封装类
        return Result.success(userClassRelationService.getUserClassRelationVOPage(userClassRelationPage, request));
    }

    /**
     * 编辑用户班级关系（给用户使用）
     *
     * @param userClassRelationEditRequest
     * @param request
     * @return
     */
    @PostMapping("/edit")
    public BaseResponse<Boolean> editUserClassRelation(@RequestBody UserClassRelationEditRequest userClassRelationEditRequest, HttpServletRequest request) {
        if (userClassRelationEditRequest == null || userClassRelationEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        UserClassRelation userClassRelation = new UserClassRelation();
        BeanUtils.copyProperties(userClassRelationEditRequest, userClassRelation);
        // 数据校验
        userClassRelationService.validUserClassRelation(userClassRelation, false);
        User loginUser = userService.getLoginUser(request);
        // 判断是否存在
        long id = userClassRelationEditRequest.getId();
        UserClassRelation oldUserClassRelation = userClassRelationService.getById(id);
        ThrowUtils.throwIf(oldUserClassRelation == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldUserClassRelation.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = userClassRelationService.updateById(userClassRelation);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return Result.success(true);
    }

    /**
     * 日新增统计用户班级关系
     *
     * @return
     */
    @PostMapping("/day/newly/added")
    public BaseResponse<List<DataGroupByDateDTO>> dayNewlyAddedUserClassRelation() {
        // 今天
        Date endDate = DateUtils.getNow();
        // 30天以前
        Date beginDate = DateUtils.dayAfter(endDate, -30);
        // 查询
        List<DataGroupByDateDTO> userClassRelationDataList = userClassRelationService.countByDay(beginDate, endDate);
        //返回结果
        return Result.success(userClassRelationDataList);

    }

    // endregion
}
